import React, {useEffect, useState} from 'react';
import {Button, Grid, Paper, TextField, Tooltip, Typography} from "@material-ui/core";
import {countWords, scrollToTop} from "../../../../../assets/functions/functions";
import {v4 as uuid4} from "uuid";
import {
  confirmQuestionName,
  createNewQuestion,
  getAllIndicators,
  setValidateQuestion,
  validateQuestion,
  validateQuestionName
} from "../../../../../redux/reducers/gqiEditor";
import {useDispatch, useSelector} from "react-redux";
import {makeStyles} from "@material-ui/core/styles";
import SnackbarMessage from "../../Common/Snackbar/SnackbarMessage";
import CircularProgress from "@material-ui/core/CircularProgress";
import CheckIcon from '@material-ui/icons/Check';
import ErrorOutlineIcon from '@material-ui/icons/ErrorOutline';


const useStyles = makeStyles(theme => ({
  gutter: {
    margin: theme.spacing(2, 0, 2, 0)
  },
  buttonSpacing: {
    marginRight: theme.spacing(1)
  },
  gutterBottom: {
    margin: theme.spacing(0, 0, 2, 0)
  },
  clearButton: {
    height: theme.spacing(8)
  },
  validationCheck: {
    marginLeft: theme.spacing(2)
  },
  validationTrue: {
    color: theme.palette.success.main
  },
  textField: {
    padding: theme.spacing(0, 2, 0, 1)
  }
}))

export default function Question(props) {
  // props
  const {handleStepForward, handleStepBackward} = props;

  // constants from redux
  const validQuestion = useSelector((state) => state.gqiEditor.common.validQuestion);
  const typedQuestion = useSelector(state => state.gqiEditor.common.typedQuestion);
  const questionAvailable = useSelector(state => state.gqiEditor.fetchedData.questionAvailable);
  const indicatorsData = useSelector((state) => state.gqiEditor.fetchedData.indicators);

  // Local constants
  const dispatch = useDispatch();
  const styles = useStyles();
  const [question, setQuestion] = useState(typedQuestion ? typedQuestion : "");
  const [loading, setLoading] = useState(false);
  const [hover, setHover] = useState(2);
  const [errorPopup, setErrorPopup] = useState(false);
  const [errors, setErrors] = useState({
    error: false,
    errorMessage: "",
  });

  useEffect(() => {
    scrollToTop();
    let interval;
    if (question.length >= 5) {
      interval = setTimeout(() => {
        dispatch(validateQuestion(question));
        setLoading(false);
      }, 2000);
    }
    return () => clearTimeout(interval)
  }, [question])


  const submitQuestion = async (e) => {
    e.preventDefault();

    if (countWords(question) < 3) {
      setErrors({
        ...errors,
        errorMessage: "The question is too short! Describe with at least four words in a sentence!"
      });
      setErrorPopup(!errorPopup);
    } else if (validQuestion) {
      handleSelectQuestion();
      dispatch(validateQuestionName(question, true));
      dispatch(confirmQuestionName(question, true));
      handleStepForward();
    }
  }

  const handleSelectQuestion = () => {
    const newQuestion = {};
    newQuestion["id"] = uuid4();
    newQuestion["name"] = question;
    newQuestion["indicatorCount"] = 0;
    dispatch(createNewQuestion(newQuestion));
    if (indicatorsData.length === 0) {
      dispatch(getAllIndicators());
    }
  }

  const handleQuestion = (e) => {
    setQuestion(e.target.value);
    if (validQuestion !== undefined)
      dispatch(setValidateQuestion(undefined));
    if (question.length >= 5) {
      setLoading(true);
    } else
      setLoading(false);

    if (question && errors.error) {
      setErrors({
        ...errors,
        error: !errors.error,
        errorMessage: ""
      });
    }
    if (questionAvailable !== 0)
      dispatch(validateQuestionName(e.target.value, 0));
  };

  return (
    <>
      <Grid container direction="column" lg={9}>
        <form onSubmit={submitQuestion}>
          <Paper elevation={hover} onMouseEnter={() => setHover(5)} onMouseLeave={() => setHover(2)}>
            <Grid container alignItems="center" className={styles.clearButton}>

              {loading ? (
                <Grid item className={styles.validationCheck}>
                  <CircularProgress size={25}/>
                </Grid>
              ) : <></>}

              <Grid item className={styles.validationCheck}>
                {validQuestion !== undefined ? validQuestion ? <>
                    <Tooltip arrow title="This question is available!">
                      <CheckIcon className={styles.validationTrue}/>
                    </Tooltip>

                  </> :
                  <Tooltip arrow title="This question is not available! Please rephrase your question.">
                    <ErrorOutlineIcon color="secondary"/>
                  </Tooltip> :
                  <></>
                }
              </Grid>

              <Grid item xs className={styles.textField}>
                <TextField
                  autoFocus
                  name="question"
                  value={question}
                  onChange={handleQuestion}
                  placeholder="e.g. How active are my students in the class?"
                  fullWidth error={errors.error}
                  helperText={errors.error ? errors.errorMessage : ""}
                />
              </Grid>
            </Grid>
          </Paper>
        </form>
      </Grid>

      <Grid container alignItems="center" className={styles.gutter} lg={9}>

        <Grid item>
          <Button onClick={handleStepBackward} className={styles.buttonSpacing}> Back </Button>
          <Button variant="contained" color="primary" disabled={!validQuestion} onClick={submitQuestion}
                  className={styles.buttonSpacing}> Next </Button>
        </Grid>
      </Grid>


      <SnackbarMessage
        message={errors.errorMessage}
        type={"error"}
        openSnackbar={errorPopup}
        setOpenSnackbar={setErrorPopup}
        duration={3000}
      />
    </>
  )
}
